package com.javabasic.algorithm.sword_of_offer;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @author mir.xiong
 * @version 1.0
 * @description
 * @see
 * @since Created by work on 2022/1/10 11:30 下午
 */
public class 剑指_Offer_50_第一个只出现一次的字符 {

    /**
     * LinkedHashMap+遍历
     * @param s
     * @return
     */
    public char firstUniqChar(String s) {
        int len = s.length(), tag, value;

        LinkedHashMap<Integer, Integer> linkedHashMap = new LinkedHashMap<>();

        for (int i = 0; i < len; i++) {
            tag = s.charAt(i)-'a';
            value = linkedHashMap.getOrDefault(tag,0);
            value++;
            linkedHashMap.put(tag,value);
        }

        for (Map.Entry<Integer, Integer> entry : linkedHashMap.entrySet()) {
            if (entry.getValue() == 1) {
                char result = (char) ('a' + entry.getKey());
                return result;
            }
        }
        return ' ';
    }


    /**
     * 思维转换
     * @param s
     * @return
     */
    public char firstUniqChar2(String s) {
        int len = s.length(), tag;
        int[] arr = new int[26];
        for (int i = 0; i < len; i++) {
            tag = s.charAt(i)-'a';
            arr[tag]++;
        }
        for (int i = 0; i < len; i++) {
            tag = s.charAt(i)-'a';
            if(arr[tag] == 1) {
                return s.charAt(i);
            }
        }
        return ' ';
    }
}
